package com.tfblog.blog.controller;


import com.tfblog.blog.annotation.PassToken;
import com.tfblog.blog.annotation.UserLoginToken;
import com.tfblog.blog.component.TokenCreater;
import com.tfblog.blog.entity.User;
import com.tfblog.blog.service.UserService;
import com.tfblog.blog.utils.TokenUtils;
import com.tfblog.blog.vo.UserVO;
import com.tfblog.utils.MD5Utils;
import com.tfblog.utils.Msg;
import com.tfblog.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tfeng
 * @since 2021-04-26
 */

@RestController
@RequestMapping("/admin")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    TokenCreater tokenCreater;

    @PassToken
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public R login(@RequestParam String username, @RequestParam String password, HttpServletResponse response, HttpServletRequest request) {
        //根据用户名查询对应的用户
        User userBase = userService.findByUsername(username);
        if (userBase != null) {
            //说明数据库存在该用户,通过MD5Utils工具类编码输入的密码,和数据库中的密码进行对比
            String code = MD5Utils.code(password);
            if (!userBase.getPassword().equals(code)) {
                //密码不正确...
                return R.ok().putStatus("密码错误",404);
            }else {
                //利用JWT生成一个token令牌
                String token = tokenCreater.getToken(userBase);
                String allowHeaders = "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, " +
                        "Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization";
                response.addHeader("Access-Control-Allow-Headers",allowHeaders);
                return R.ok().put("token",token).putStatus("登录成功",200);
            }
        }else {
            //说明不存在该用户
            return R.ok().putStatus("该用户不存在",404);
        }

    }

    /*
    * 该请求需要验证token才能访问
    * */
    @UserLoginToken
    @RequestMapping(value = "/loginToken",method = RequestMethod.POST)
    public R loginToken() {
        //通过token令牌验证,直接返回200状态码--表示验证成功...
        return R.ok().putStatus("您已验证token成功",200);
    }

}

